import React, { Component } from 'react'
import ProductList from './subs/ProductList'
import CarList from './subs/CarList'
import styles from "../assets/styles/shopping.module.css"

export default class TabE extends Component {
  state = {
    // 课程数据
    courseList: [
      {
        id: 1,
        imgname: 'https://img1.baidu.com/it/u=1000375653,4052007938&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=652',
        title: 'Python实战开发',
        content: '精通Python学习指南',
        price: 234
      },
      {
        id: 2,
        imgname: 'https://img1.baidu.com/it/u=1000375653,4052007938&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=652',
        title: 'Java实战开发',
        content: '精通Java学习指南',
        price: 674
      },
      {
        id: 3,
        imgname: 'https://img1.baidu.com/it/u=1000375653,4052007938&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=652',
        title: 'H5实战开发',
        content: '精通H5学习指南',
        price: 345
      },
      {
        id: 4,
        imgname: 'https://img1.baidu.com/it/u=1000375653,4052007938&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=652',
        title: '测试框架开发',
        content: '精通测试框架学习指南',
        price: 123
      }
    ],
    // 购物车数据
    cartList: [

    ]
  }

  getProductId = (id) => {
    const { courseList, cartList } = this.state
    //拿到了id后，先判断
    const index = cartList.findIndex(item => item.id == id)
    console.log(index);
    if (index != -1) {
      alert("商品已经存在")
    } else {
      //加入购物车
      const obj = courseList.find(item => item.id === id)
      obj.count = 1
      //选中状态
      obj.status = false
      cartList.push(obj)
      this.setState({
        cartList
      })
    }

  }
  changeCount = (id) => {
    const { cartList } = this.state
    //product实际上地址
    const product = cartList.find(item => item.id === id)
    product.count++
    this.setState({
      cartList
    })
  }
  changeCount2 = (id, value) => {
    const { cartList } = this.state
    //product实际上地址
    const product = cartList.find(item => item.id === id)
    product.count = value
    this.setState({
      cartList
    })
  }
  changeStatus = (id,bool)=>{
    const { cartList } = this.state
    //product实际上地址
    const product = cartList.find(item => item.id === id)
    product.status = bool
    this.setState({
      cartList
    })
  }

  render() {
    const { courseList, cartList } = this.state
    return (
      <div className={styles.container}>
        <h2>产品</h2>
        {/* 引入产品渲染 */}
        <ProductList list={courseList} getProductId={this.getProductId}></ProductList>
        <h2>购物车</h2>
        {/* 引入购物车渲染 */}
        <CarList changeStatus={this.changeStatus} list={cartList} changeCount2={this.changeCount2} changeCount={this.changeCount}></CarList>
        
      </div>
    )
  }
}
